package com.javafactroy.kunlong.bip.icp.message.base.codec;

import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.*;

public class DelimiterBasedFrameDecoder {
    final static String LINE_WINDOWS_CHAR="\r\n";
    final static String LINE_LINUX_CHAR="\r\n";

    //DelimiterBasedFrameDecoder
    String[] decode(byte[] msg) {
        try {
            return StringUtils.split(new String(msg, "utf-8"), LINE_WINDOWS_CHAR);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static List<byte[]> decode(byte[] bytes, byte delimiter) {
        List<byte[]> list = new ArrayList<>();
        int start = 0;
        for (int i = 0; i < bytes.length; i++) {
            if (bytes[i] == delimiter || i == bytes.length - 1) {
                list.add(Arrays.copyOfRange(bytes, start, i));
                start = i + 1;
            }
        }
        return list;
    }

    static boolean same(byte[] bytes, int start, byte[] delimiter) {
        boolean ok = true;

        for (int i = 0; i < delimiter.length; i++) {
            ok = ok && bytes[start + i] == delimiter[i];
        }

        return ok;
    }

    public static List<byte[]> decode(byte[] bytes, byte[] delimiter) {
        List<byte[]> list = new ArrayList<>();
        int start = 0;
        for (int i = 0; i < bytes.length - delimiter.length + 1; i++) {
            if (same(bytes, i, delimiter)) {
                list.add(Arrays.copyOfRange(bytes, start, i));
                start = i + delimiter.length;
            }
        }
        return list;
    }

    public static Map<String, String> list2MapStr(List<byte[]> params) {
        Map<String, String> map = new LinkedHashMap<>();
        String key = "";
        int i = 0;
        for (byte[] item : params) {
            if (i % 2 == 0) {
                key = new String(item);
            } else {
                map.put(key, new String(item));
            }
            i++;

        }
        return map;

    }

    public static int findIndex(List<String> titles, String title) {
        return titles.indexOf(title);
    }
    public static int findIndex(Set<String> titles, String title) {
        List<String > l=new ArrayList<>( );
        l.addAll(titles);
        return l.indexOf(title);
    }

    public static int findIndex(List<byte[]> titles, byte[] title) {
        return titles.indexOf(title);
    }

    public static void main(String[] args) {
        String aa = "name\r\nleijmdas\r\naddr\r\nsz\r\n";
        List<byte[]> list = decode(aa.getBytes(), "\r\n".getBytes());
        String[] ss = StringUtils.split(aa, "\r\n" );
        int i = findIndex(list2MapStr(list).keySet(), "addr"  );
        System.out.println(i);
        for (Map.Entry<String, String> e : list2MapStr(list).entrySet()) {
            System.err.println(e);
        }
    }
}
